package cn.edu.scnu.utils;

import cn.edu.scnu.exception.NoLoginException;
import cn.edu.scnu.vo.SysResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;

public class RestTemplateUtils {
    public static SysResult exchangeWithToken(RestTemplate restTemplate, HttpServletRequest httpServletRequest, String url, HttpMethod httpMethod) throws Exception {
        String ticket = httpServletRequest.getHeader("token");
        if (StringUtils.isEmpty(ticket)) {
            throw new NoLoginException("未登录");
        }
        HttpHeaders headers = new HttpHeaders();
        headers.set("token", ticket);
        HttpEntity httpEntity = new HttpEntity(null, headers);
        ResponseEntity<SysResult> exchange = restTemplate.exchange(url, httpMethod, httpEntity, SysResult.class);
        if (exchange.getStatusCode() == HttpStatus.OK) {
            return exchange.getBody();
        }
        throw new Exception("服务器内部错误");
    }
}
